<template>
  <div class="search-suggestion">
    <van-cell
      v-for="(text, index) in suggestions"
      :key="index"
      icon="search"
      @click="$emit('search', text)"
    >
      <div slot="title" v-html="highlight(text)"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestion } from "@/api/search.js";

// 按需加载，加载防抖
import { debounce } from "lodash";

export default {
  name: "SearchSuggestion",
  components: {},
  props: {
    searchText: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      // 联想建议
      suggestions: [],
    };
  },
  computed: {},
  watch: {
    searchText: {
      // 监视的处理函数,输入框内容发生变化，就会触发这个函数
      // 防抖：
      // 参数1：一个函数
      // 参数2：延迟的时间，单位是毫秒
      // 返回值：防抖之后的函数
      handler: debounce(function(val) {
        // console.log(val);
        this.locadSearchSuggestion(val);
        console.log(val);
      }, 500),

      // 首次监视触发,立即触发
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    async locadSearchSuggestion(q) {
      try {
        const { data } = await getSearchSuggestion(q);
        this.suggestions = data.data.options;
      } catch {
        this.$toast("获取失败");
      }
    },

    // 替换字符高亮
    highlight(text) {
      const highlight = `<span class="active">${this.searchText}</span>`;

      const reg = new RegExp(this.searchText, "gi");

      return text.replace(reg, highlight);
    },
  },
};
</script>

<style scoped lang="less">
.search-suggestion {
  /deep/ span.active {
    color: #3296fa;
  }
}
</style>
